package com.scm.biz.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.OrderPattern;
import com.scm.biz.bean.ProductionBeforePatternSize;
import com.scm.biz.bean.ProductionOrder;
import com.scm.biz.bean.ProductionPattern;
import com.scm.biz.bean.ProductionPatternSize;
import com.scm.biz.bean.SysRole;
import com.scm.biz.bean.SysUser;
import com.scm.biz.dao.CustomerDao;
import com.scm.biz.dao.OrderDao;
import com.scm.biz.dto.MsgNoticeDto;
import com.scm.biz.dto.ProductionNoticeDto;
import com.scm.biz.dto.ProductionOrderDto;
import com.scm.biz.enums.FileCategoryEnum;
import com.scm.biz.enums.OrderTypeEnum;
import com.scm.biz.query.FactoryQuery;
import com.scm.biz.query.ProductionOrderQuery;
import com.scm.biz.result.ProductionDetailResult;
import com.scm.biz.result.ProductionNoticeResult;
import com.scm.biz.result.ProductionOrderResult;
import com.scm.biz.result.ProofingOrderResult;
import com.scm.biz.service.BusinessFileService;
import com.scm.biz.service.CustomerService;
import com.scm.biz.service.FactoryService;
import com.scm.biz.service.MsgNoticeService;
import com.scm.biz.service.OrderService;
import com.scm.biz.service.ProductionOrderService;
import com.scm.biz.service.ProductionPatternService;
import com.scm.biz.service.ProofingOrderService;
import com.scm.biz.service.SysUserService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.core.bean.resp.RespBean;
import com.scm.utils.Const;
import com.scm.utils.UfdmDateUtil;
import com.scm.utils.UploadAndDownUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/productionorder")
public class ProductionOrderAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3900326036654169060L;
	@Resource
	ProductionOrderService productionOrderService;
	@Resource
	FactoryService factoryService;
	@Resource
	CustomerService customerService;
	@Resource
	OrderService orderService;
	@Resource
	ProductionPatternService productionPatternService;
	@Resource
	ProofingOrderService proofingOrderService;
	@Autowired
	BusinessFileService businessFileService;
	@Resource
	SysUserService sysUserService;
	@Autowired
	CustomerDao customerDao;
	@Autowired
	MsgNoticeService msgNoticeService;
	@Autowired
	OrderDao orderDao;
	/**
	 * 展示打样订单列表
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView doList(ProductionOrderQuery productionOrderQuery,HttpServletRequest req){
		if(productionOrderQuery.getPageNo()==0){
			productionOrderQuery.setPageNo(1);
		}
		List<SysRole> sysRoleList = (List<SysRole>)SecurityUtils.getSubject().getSession().getAttribute("_roleList");
		//判断是否为设计总监或者供应链总监
		for(SysRole sysRole:sysRoleList){
			if(sysRole.getCode().equals("R007") || sysRole.getCode().equals("R001")){
				productionOrderQuery.setIsOpen(1);
				break;
			}
		}
		Integer userId = Integer.valueOf(SecurityUtils.getSubject().getSession().getAttribute("userId").toString());
		
		productionOrderQuery.setPerformer(userId);
		List<ProductionOrderResult> list=productionOrderService.selectPage(productionOrderQuery);
		//大货订单总数
		productionOrderQuery.setRecourdCount(productionOrderService.selectTotal(productionOrderQuery));
		
		ModelAndView mav=new ModelAndView("order/production_list");
		//所有工厂
		mav.addObject("factoryList",factoryService.selectList(new FactoryQuery()));
		//所有项目经理
		mav.addObject("managerList", sysUserService.getManager());
		//所有销售
		mav.addObject("saleList", sysUserService.getSale());
		//订单编号
		mav.addObject("code", productionOrderQuery.getCode());
		//客户名称或简称
		mav.addObject("customerName",productionOrderQuery.getCustomerName());
		//工厂Id
		mav.addObject("factoryId", productionOrderQuery.getFactoryId());
		//项目经理Id
		mav.addObject("managerId", productionOrderQuery.getManagerId());
		//销售Id
		mav.addObject("saleId", productionOrderQuery.getSaleId());
		mav.addObject("productionOrders",list);
		mav.addObject("status",productionOrderQuery.getStatus());
		mav.addObject("splitPage", productionOrderQuery.getSplitPage());
		mav.addObject("url", Const.getPath(req));
		return mav;
	}
	@RequestMapping("/create")
	public ModelAndView doShowProofingOrderAddPage(Long orderId,Long proofingOrderId){
		ModelAndView mvAndView = new ModelAndView("order/production_add");
		ProofingOrderResult proofingOrderResult = proofingOrderService.selectById(proofingOrderId);
		mvAndView.addObject("customer",proofingOrderResult.getCustomer());
		mvAndView.addObject("orderId",orderId);
		mvAndView.addObject("proofingOrderResult",proofingOrderResult);
		return mvAndView;
	}
	@RequestMapping("/detail")
	public ModelAndView doDetail(Long id){
		ModelAndView mvAndView = new ModelAndView("order/production_detail");
		ProductionOrderResult productionOrderResult = productionOrderService.selectById(id);
		mvAndView.addObject("productionOrderResult",productionOrderResult);
		return mvAndView;
	}
	@RequestMapping("/insert")
	@ResponseBody
	public RespBean<String> doInsert(ProductionOrderDto productionOrderDto,MultipartFile file) throws UfdmException{
		RespBean<String> respBean=new RespBean<String>();
		if(productionOrderDto.getEnddate()==null||productionOrderDto.getEnddate().isEmpty()){
			throw new UfdmException("截止时间不能为空");
		}
		if(productionOrderDto.getPatternSizeList()==null||productionOrderDto.getPatternSizeList().size()==0){
			throw new UfdmException("款式不能为空");
		}
		productionOrderService.insert(productionOrderDto,file);
		
		return respBean;
	}
	@RequestMapping("/saveSaleContact")
	@ResponseBody
	public RespBean<String> saveSaleContact(Long id,MultipartFile contactFile) throws UfdmException{
		RespBean<String> respBean=new RespBean<String>();
		businessFileService.removeByBusinesId(id, FileCategoryEnum.PRODUCTION_CONTACT_SALE_FILE.value());
		businessFileService.insert(contactFile, id, FileCategoryEnum.PRODUCTION_CONTACT_SALE_FILE.value(), 0);
		
		return respBean;
	}
	
	
	@RequestMapping("/addProductionNotice")
	public ModelAndView createProductionNotice(String ids,Integer index){
		ModelAndView mv = new ModelAndView("order/production_order_notice");
		if(ids!=null){
			String arrayStr[]  = ids.split(",");
			List<String> idList = Arrays.asList(arrayStr);
			List<Long> productionPatternId = new ArrayList<Long>();
			if(index!=null){
				String str = idList.get(index);
				Long id = Long.valueOf(str);
				productionPatternId.add(id);
			}else{
				for(String str: idList){
					Long id = Long.valueOf(str);
					productionPatternId.add(id);
				}
			}
			List<ProductionDetailResult> productionDetailResults = productionPatternService.selectProductionDetail(productionPatternId);
			mv.addObject("productionDetailResults", productionDetailResults);
			mv.addObject("factorires",factoryService.selectList(null));
			mv.addObject("ids",ids);
			mv.addObject("index",index);
		}
		return mv;
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public RespBean<String> editProductionNotice(MultipartHttpServletRequest req) throws Exception{
		RespBean<String> respBean = new RespBean<String>();
		String json = req.getParameter("productions");

		JSONArray array = JSONArray.fromObject(json);
		List<ProductionNoticeDto> productionNoticeDtos = parseProductionNotice(array,req);
		productionPatternService.insertProductionNotice(productionNoticeDtos);
		respBean.setBody("保存成功");
		return respBean;
	}

	
	@RequestMapping("/showNotices")
	public ModelAndView showNotices(String ids,Integer index){
		ModelAndView mv = new ModelAndView("order/production_notice_preview");
		if(ids!=null){
			String arrayStr[]  = ids.split(",");
			List<String> idList = Arrays.asList(arrayStr);
			List<Long> productionPatternId = new ArrayList<Long>();
			for(String str: idList){
				Long id = Long.valueOf(str);
				productionPatternId.add(id);
			}
			List<ProductionNoticeResult> productionNoticeList = productionPatternService.selectProdutionNotice(productionPatternId);
			mv.addObject("ids", ids);
			mv.addObject("index", index);
			if(productionNoticeList!=null&&productionNoticeList.size()!=0){
				mv.addObject("id", productionNoticeList.get(0).getOrderId());
				mv.addObject("productionNoticeList", productionNoticeList);
			}
		}
		return mv;
	}
	
	/**
	 * 生成大货生产通知单成功
	 * @return
	 */
	@RequestMapping("/generateSuccess")
	public ModelAndView generateSuccess(Long id,String ids){
		ModelAndView mv=new ModelAndView("order/production_order_info_success");
		mv.addObject("id",id);
		mv.addObject("ids",ids);
		return mv;
	}
	
	/**
	 * 产生PDF文件
	 * @param request
	 * @param response
	 * @return
	 * @throws UfdmException 
	 * @throws Exception 
	 */
	@RequestMapping("/exportPdf")
	@ResponseBody
	public RespBean<String> expoprtPdf(MultipartHttpServletRequest request, HttpServletResponse response) throws UfdmException{
		UploadAndDownUtil.expoprtPdf("/pdf/dh",request,response);
		RespBean<String> respBean=new RespBean<String>();
		return respBean;
	}
	
	/**
	 * 下载打样通知单
	 * @param id
	 * @param req
	 * @param res
	 * @throws UfdmException
	 */
	@RequestMapping("/downPdf")
	public void DownPdf(String id,HttpServletRequest req, HttpServletResponse res) throws UfdmException{
		UploadAndDownUtil.downFile("大货通知单"+id+".pdf", "/pdf/dh"+id+".pdf", req, res);
	}
	
	

	private List<ProductionNoticeDto> parseProductionNotice(JSONArray array,MultipartHttpServletRequest req) throws Exception {
		List<ProductionNoticeDto> productionNoticeDtos = new ArrayList<ProductionNoticeDto>();
		//解析页面传输的json数据
		for(int i=0;i<array.size();i++){
			int num = i+1;
			ProductionNoticeDto productionNoticeDto = new ProductionNoticeDto();
			OrderPattern orderPattern = new OrderPattern();
			ProductionPattern productionPattern = new ProductionPattern();
			JSONObject object = array.getJSONObject(i);
			//大货款式Id
			Integer id = object.getInt("id");
			productionNoticeDto.setId(id);
			productionPattern.setId((long)id);
			
			if(object.getInt("factoryId")==0){
				 throw new UfdmException("第"+num+"款工厂不能为空");
			}
			//工厂Id
			Integer factoryId = object.getInt("factoryId");
			
			
			productionPattern.setFactoryId(factoryId);
			
			
			ProductionPattern pp = productionPatternService.selectById(Long.valueOf(id));
			if(pp.getFactoryId() ==null || factoryId !=pp.getFactoryId()){
				/********************消息***************/
				ProductionOrder productionOrder= productionOrderService.selectByPk(pp.getProductionOrderId());
				SysUser sysUser = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("sysUser");
				MsgNoticeDto msgNoticeDto = new MsgNoticeDto();
				msgNoticeDto.setTitle("工厂已安排，请上传尺码表");
				msgNoticeDto.setContent(sysUser.getName()+"已经安排了"+customerDao.selectByPrimaryKey(orderDao.selectByPrimaryKey(productionOrder.getOrderId()).getCustomerId().intValue()).getFullname()
										+ "客户的大货工厂，请尽快上传推码表，截止时间为"+UfdmDateUtil.dateToString(productionOrder.getEnddate(), "MM月dd日"));
				msgNoticeDto.setOrderType(OrderTypeEnum.T3.toString());
				msgNoticeDto.setTaskId(productionOrder.getId());
				msgNoticeDto.setUserType(1);
				msgNoticeService.insert(msgNoticeDto,"R005");
				
				msgNoticeDto.setTitle("工厂已安排");
				msgNoticeDto.setContent(sysUser.getName()+"已经安排了"+customerDao.selectByPrimaryKey(orderDao.selectByPrimaryKey(productionOrder.getOrderId()).getCustomerId().intValue()).getFullname()
										+ "客户的大货工厂，请尽快上传推码表，截止时间为"+UfdmDateUtil.dateToString(productionOrder.getEnddate(), "MM月dd日"));
				msgNoticeDto.setUserType(0);
				msgNoticeService.insert(msgNoticeDto,productionOrder.getCreator());
			}
			if(object.getString("productionEndDate")==null||object.getString("productionEndDate").isEmpty()){
				throw new UfdmException("第"+num+"款工厂交期不能为空");
			}
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			System.out.println("\n"+object.getString("productionEndDate"));
			//工厂交货日期
			productionPattern.setDeliveryDate(fmt.parse(object.getString("productionEndDate")));
			System.out.println("\n"+productionPattern.getDeliveryDate());
			//是否有样衣
			productionPattern.setIsExists(object.getString("isExists"));
			//设计款式说明
			productionPattern.setDescription(object.getString("description"));
			//产前样数量
			JSONArray beforePattern = object.getJSONArray("beforePatterns");
			List<ProductionBeforePatternSize> beforePatternSizes = new ArrayList<ProductionBeforePatternSize>();
			for(int j=0;j<beforePattern.size();j++){
				ProductionBeforePatternSize beforePatternSize = new ProductionBeforePatternSize();
				JSONObject beforeObject = beforePattern.getJSONObject(j);
				String count = beforeObject.getString("count");
				if(count==null||count.equals("0")||count.isEmpty()){
					continue;
				}
				beforePatternSize.setColor(beforeObject.getString("color"));
				String xs = beforeObject.getString("xs");
				if(xs!=null&&!xs.isEmpty()){
					beforePatternSize.setXsAmount(Integer.parseInt(xs));
				}
				String s = beforeObject.getString("s");
				if(s!=null&&!s.isEmpty()){
					beforePatternSize.setsAmount(Integer.parseInt(s));
				}
				String m = beforeObject.getString("m");
				if(m!=null&&!m.isEmpty()){
					beforePatternSize.setmAmount(Integer.parseInt(m));
				}
				String l = beforeObject.getString("l");
				if(l!=null&&!l.isEmpty()){
					beforePatternSize.setlAmount(Integer.parseInt(l));
				}
				String xl = beforeObject.getString("xl");
				if(xl!=null&&!xl.isEmpty()){
					beforePatternSize.setXlAmount(Integer.parseInt(xl));
				}
				beforePatternSize.setProductionPatternId(id);
				beforePatternSizes.add(beforePatternSize);
			}
			//大货尺码数量
			JSONArray pattern = object.getJSONArray("patterns");
			List<ProductionPatternSize> patternSizes = new ArrayList<ProductionPatternSize>();
			for(int j=0;j<pattern.size();j++){
				int num2 = j+1;
				ProductionPatternSize patternSize = new ProductionPatternSize();
				JSONObject patternObject = pattern.getJSONObject(j);
				if(patternObject.getString("color")==null||patternObject.getString("color").isEmpty()){
					throw new UfdmException("第"+num+"款，第"+num2+"行大货款式颜色不能为空");
				}
				if(patternObject.getString("count")==null||patternObject.getString("count").equals("0")||patternObject.getString("count").isEmpty()){
					throw new UfdmException("第"+num+"款，第"+num2+"行大货款式数量不能为空");
				}
				if(patternObject.getString("price")==null||patternObject.getString("price").equals("0")||patternObject.getString("price").isEmpty()){
					throw new UfdmException("第"+num+"款，第"+num2+"行单价不能为空");
				}
				if(patternObject.getString("arrivelocation")==null||patternObject.getString("arrivelocation").equals("0")||patternObject.getString("arrivelocation").isEmpty()){
					throw new UfdmException("第"+num+"款，第"+num2+"行到货地点不能为空");
				}
				patternSize.setColor(patternObject.getString("color"));
				String xs = patternObject.getString("xs");
				if(xs!=null&&!xs.isEmpty()){
					patternSize.setXsAmount(Integer.parseInt(xs));
				}
				String s = patternObject.getString("s");
				if(s!=null&&!s.isEmpty()){
					patternSize.setsAmount(Integer.parseInt(s));
				}
				String m = patternObject.getString("m");
				if(m!=null&&!m.isEmpty()){
					patternSize.setmAmount(Integer.parseInt(m));
				}
				String l = patternObject.getString("l");
				if(l!=null&&!l.isEmpty()){
					patternSize.setlAmount(Integer.parseInt(l));
				}
				String xl = patternObject.getString("xl");
				if(xl!=null&&!xl.isEmpty()){
					patternSize.setXlAmount(Integer.parseInt(xl));
				}
				patternSize.setProductionPatternId((long)id);
				String price = patternObject.getString("price");
				if(price!=null&&!price.isEmpty()){
					patternSize.setPrice(Double.parseDouble(price));
				}
				patternSize.setArriveAddress(patternObject.getString("arrivelocation"));
				patternSizes.add(patternSize);
			}
			//款式细节明细
			orderPattern.setDetailDescription(object.getString("detailDescription"));
			//面辅料明细
			orderPattern.setAccessoryDetail(object.getString("accessoryDetail"));
			//折叠方法
			if(object.getString("foldMethod")==null||object.getString("foldMethod").isEmpty()){
				throw new UfdmException("第"+num+"款折叠方法不能为空");
			}
			orderPattern.setFoldMethodOther(object.getString("foldMethod"));
			
			//包装方法
			if(object.getString("packageMethod")==null||object.getString("packageMethod").isEmpty()){
				throw new UfdmException("第"+num+"款包装方法不能为空");
			}
			orderPattern.setPackageMethodOther(object.getString("packageMethod"));
			
			//验货标准
			if(object.getString("checkStandard")==null||object.getString("checkStandard").isEmpty()){
				throw new UfdmException("第"+num+"款验货标准不能为空");
			}
			orderPattern.setCheckStandardOther(object.getString("checkStandard"));
			
			//测试要求
			if(object.getString("testRequest")==null||object.getString("testRequest").isEmpty()){
				throw new UfdmException("第"+num+"款测试要求不能为空");
			}
			orderPattern.setTestRequest(object.getString("testRequest"));
			
			//中查
			if(object.getString("middleCheck")==null||object.getString("middleCheck").isEmpty()){
				throw new UfdmException("第"+num+"款中查人员不能为空");
			}
			orderPattern.setMiddleCheck(object.getString("middleCheck"));
			
			//尾查
			if(object.getString("lastCheck")==null||object.getString("lastCheck").isEmpty()){
				throw new UfdmException("第"+num+"款尾查人员不能为空");
			}
			orderPattern.setLastCheck(object.getString("lastCheck"));
			
			//第三方验货
			if(object.getString("thirdparty")==null||object.getString("thirdparty").isEmpty()){
				throw new UfdmException("第"+num+"款第三方验货人员不能为空");
			}
			orderPattern.setThirdparty(object.getString("thirdparty"));
			
			//备注
			orderPattern.setMemo(object.getString("memo"));
			productionNoticeDto.setOrderPattern(orderPattern);
			productionNoticeDto.setProductionBeforePatternSizes(beforePatternSizes);
			productionNoticeDto.setProductionPattern(productionPattern);
			productionNoticeDto.setProductionPatternSizes(patternSizes);
			//大货合同
			MultipartFile file=req.getFile("file"+i);
			productionNoticeDto.setFile(file);
			productionNoticeDtos.add(productionNoticeDto);
		}
		return productionNoticeDtos;
	}
}
